package postlogic

import (
	"context"

	userpostlogic "go-zero-admin/apps/system/cmd/rpc/internal/logic/userpost"
	"go-zero-admin/apps/system/cmd/rpc/internal/svc"
	"go-zero-admin/apps/system/cmd/rpc/syspb"
	"go-zero-admin/apps/system/model"
	"go-zero-admin/pkg/tool"
	"go-zero-admin/pkg/xerr"

	"github.com/Masterminds/squirrel"
	"github.com/duke-git/lancet/v2/convertor"
	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type DelPostLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
	getUserPostList *userpostlogic.GetUserPostListLogic
}

func NewDelPostLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DelPostLogic {
	return &DelPostLogic{
		ctx:             ctx,
		svcCtx:          svcCtx,
		Logger:          logx.WithContext(ctx),
		getUserPostList: userpostlogic.NewGetUserPostListLogic(ctx, svcCtx),
	}
}

func (l *DelPostLogic) DelPost(in *syspb.DelPostReq) (*syspb.DelPostResp, error) {
	if len(in.GetIds()) == 0 || (!in.GetIsDel() && in.GetUpdateUser() == "") {
		return nil, errors.Wrapf(xerr.NewErrMsg("删除岗位失败：参数错误"),
			tool.GetErrMsgFormat("delete post"), "params is not existed", in)
	}

	// 校验参数
	for _, v := range in.GetIds() {
		// 如果已分配，则不允许删除，直接使用model查询，避免循环依赖
		count, err := l.svcCtx.SysUserPostModel.FindCount(l.ctx, l.svcCtx.SysUserPostModel.CountBuilder("1").
			Where(squirrel.Eq{"post_id": v}))
		if err != nil || count > 0 {
			return nil, errors.Wrapf(xerr.NewErrMsg("删除岗位失败：岗位ID："+convertor.ToString(v)+" 已分配，不允许删除"),
				tool.GetErrMsgFormat("delete post"), "post is assigned", in)
		}
	}

	// 处理删除
	err := l.svcCtx.SysPostModel.DeleteEx(l.ctx, nil, in.GetIds(), in.GetIsDel(), in.GetUpdateUser())
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrFindOneCode(err, model.ErrNotFound),
			tool.GetErrMsgFormat("delete post"), err, in)
	}

	return &syspb.DelPostResp{}, nil
}
